
#include "mainwin.h"
#include "ui_mainwin.h"

#include <QtCore/QDebug>
#include <QSettings>
#include <QProcess>

mainWin::mainWin(QStringList argv,QWidget *parent) :
    QMainWindow(parent),
    m_ui(new Ui::mainWin)
{

    m_ui->setupUi(this);
	// icon setup
	setupTray();


	lth=new lircThread;
	lth->start();

	connect(lth,SIGNAL(keyPressed(keyData)),this,SLOT(remKey(keyData)));
	connect(lth,SIGNAL(keyRepeated(keyData)),this,SLOT(remRepeat(keyData)));
	connect(m_ui->saveBtn,SIGNAL(clicked()),this,SLOT(saveKey()));

	if (argv.contains("--active"))
		m_ui->enableBtn->setChecked(1);


}

mainWin::~mainWin()
{
	delete lth;
	delete iconMenu;
    delete m_ui;
}

void mainWin::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
void mainWin::remKey(keyData k)
{

	//qDebug()<<k.str();
	static QSettings cmd("qlirc","commands");

	m_ui->keyName->setText(k.name);
	m_ui->cmdEdit->setText(cmd.value(k.name).toString());
	QStringList args;
	if (cmd.value(k.name).toString()!="" && m_ui->enableBtn->isChecked())
	{
		args<<"-c";
		args<<cmd.value(k.name).toString();
		qDebug()<<args;
		QProcess::execute("bash",args);
	}

}
void mainWin::remRepeat(keyData k)
{

}
void mainWin::saveKey()
{
	static QSettings cmd("qlirc","commands");
	cmd.setValue(m_ui->keyName->text(),m_ui->cmdEdit->toPlainText());
}
void mainWin::toggleWin()
{
	if (isVisible())
		hide();
	else
		show();
}
void mainWin::closeEvent(QCloseEvent *ev)
{
	toggleWin();
//	ev->ignore();
	ev->accept();
}
void mainWin::setupTray()
{
	icon=new QSystemTrayIcon(QIcon(":/images/trayicon.png"),this);
	icon->show();
	icon->setToolTip("qLirc");
	connect (icon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(trayClicked(QSystemTrayIcon::ActivationReason)));
	QAction *act;

	iconMenu=new QMenu;
//	iconMenu->addAction("show",this,SLOT(show()));
	act=iconMenu->addAction("enabled");
	act->setCheckable(1);
	act->setChecked(0);
	connect (act,SIGNAL(toggled(bool)),m_ui->enableBtn,SLOT(setChecked(bool)));
	connect (m_ui->enableBtn,SIGNAL(toggled(bool)),act,SLOT(setChecked(bool)));
	iconMenu->addSeparator();
	iconMenu->addAction("exit",QApplication::instance(),SLOT(quit()));

	icon->setContextMenu(iconMenu);
}
void mainWin::trayClicked(QSystemTrayIcon::ActivationReason reason)
{
	if (reason==QSystemTrayIcon::Trigger)
		toggleWin();
}
